package com.ifar.audiosdk.base

import android.app.AlertDialog
import com.ifar.audiosdk.utils.showToast
import com.ifar.audiosdk.veiw.MMLoading
import kotlinx.coroutines.*
import kotlin.system.exitProcess

abstract class BaseActivity<VM : IfarBaseViewModel> : IfarBaseActivity<VM>() {

    //记录用户首次点击返回键的时间
    private var firstTime: Long = 0
    private lateinit var mmLoading: MMLoading
    private var loadingJob: Job? = null

    protected open fun showLoading(
        msg: String = "loading",
        await: Long = 0,
        listener: LoadingTimeOutListener? = null,
        cancelable: Boolean = false,
    ) {
        mmLoading = loadingCreate(msg, cancelable)
        mmLoading.dismiss()
        mmLoading.show()
        if (await > 0) {
            loadingJob?.cancel()
            loadingJob = GlobalScope.launch(Dispatchers.Main) {
                delay(await)
                listener?.loadTimeout()
                hideLoading()
            }
        }
    }

    private fun loadingCreate(msg: String, cancelable: Boolean): MMLoading {
        val builder = MMLoading.Builder(this)
            .setMessage(msg)
            .setCancelable(cancelable)
            .setCancelOutside(cancelable)
        return builder.create()
    }

    protected open fun hideLoading() {
        loadingJob?.cancel()
        if (mmLoading.isShowing) {
            mmLoading.dismiss()
        }
    }

    interface LoadingTimeOutListener {
        fun loadTimeout()
    }

    fun doubleOnClickExit() {
        val secondTime = System.currentTimeMillis()
        if (secondTime - firstTime > 2000) {
            showToast("再次点击返回键退出程序")
            firstTime = secondTime
        } else {
            exitProcess(0)
        }
    }

    fun finisDoubleSubmit(
        title: String = "Hint",
        msg: String = "Make sure to close the current screen ?",
    ) {
        val normalDialog: AlertDialog.Builder = AlertDialog.Builder(this)
        normalDialog.setTitle(title)
        normalDialog.setMessage(msg)
        normalDialog.setPositiveButton("sure") { dialog, _ ->
            dialog.dismiss()
            finish()
        }
        normalDialog.setNegativeButton("cancel") { dialog, _ ->
            dialog.dismiss()
        }
        normalDialog.show()
    }
}